package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.AddressBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.PickerView;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.StringUtil;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;

import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/7/10   编辑收货信息
 * Time: 15:41
 */
public class DeliveryAddressActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, default_address, text_address;
    private CheckBox cb_select;
    private ImageView preservation;
    private RelativeLayout address_selection;
    private EditText edit_name, edit_phone, edit_detailed_address;
    /*城市 省份Province  */
    private PickerView picker_province, picker_city, picker_diatrict;
    private String provinceName, cityName, diatrictName;
    private List<String> provinceList, cityList, diatrictList;
    private UtilPopupWindow popupWindow;
    private String goods_receipt_address, goods_receipt_name, goods_receipt_phone, goods_receipt_address_d;
    private String userId, token, isModify, addressId;
    private boolean isSelect;
    /*省市区*/
    private String province, city, county;

    @Override
    protected View getLayout() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        view = LayoutInflater.from(DeliveryAddressActivity.this).inflate(R.layout.activity_delivery_address, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(R.string.text_delivery_address);
        cb_select = (CheckBox) view.findViewById(R.id.cb_select);
        default_address = (TextView) view.findViewById(R.id.default_address);
        cb_select.setChecked(false);
        //选中状态发生改变后执行此监听器，两个参数，一个是对象，一个是是否选中。CompoundButton是CheckBox的超类
        CheckBoxListener cbListener = new CheckBoxListener();
        cb_select.setOnCheckedChangeListener(cbListener);
        preservation = (ImageView) view.findViewById(R.id.preservation);
        address_selection = (RelativeLayout) view.findViewById(R.id.address_selection);
        text_address = (TextView) view.findViewById(R.id.text_address);
        edit_name = (EditText) view.findViewById(R.id.edit_name);
        edit_phone = (EditText) view.findViewById(R.id.edit_phone);
        edit_detailed_address = (EditText) view.findViewById(R.id.edit_detailed_address);
        initProvinceDatas();
    }

    @Override
    protected void initListener() {

        registerClickListener(preservation, address_selection);
    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("token");
            SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).putString("isRefresh", "no");
        }
        String area = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("area");
        String areaIds = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("areaIds");
        if (area != null && !area.equals("")) {
            text_address.setText(area.replace("市辖区", ""));
            SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).putString("area", null);
        } else {
            text_address.setText(getResources().getString(R.string.text_s_s_q));
        }
        if (areaIds != null && !areaIds.equals("")) {
            String[] strs = areaIds.split(",");
            for (int i = 0, len = strs.length; i < len; i++) {
                System.out.println(strs[i].toString());
                province = strs[0].toString();
                city = strs[1].toString();
                county = strs[2].toString();
            }
            SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).putString("areaIds", null);
        }


    }

    @Override
    protected void initData() {
        userId = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).getString("token");
        Intent intent = getIntent();
        addressId = intent.getStringExtra("addressId");
        isModify = intent.getStringExtra("isModify");
        if (isModify == null) {
            isModify = "0";
        }
        isSelect = intent.getBooleanExtra("isSelect", false);
        if (isSelect == true) {
            cb_select.setChecked(true);
            default_address.setTextColor(getResources().getColor(R.color.color_333333));
            cb_select.setClickable(false);
        }
        if (addressId != null) {
            AddressBean bean = new AddressBean();
            bean.setAddressId(addressId);
            CommonInterface deliveryAddressInterface = new CommonInterface(DeliveryAddressActivity.this, httpListener);
            deliveryAddressInterface.getInterface("16012", JSON.toJSONString(bean));
        }

    }

    /*修改*/
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String addressArea = JsonUtil.getFieldValue(response, "addressArea");
                String addressDetail = JsonUtil.getFieldValue(response, "addressDetail");
                String addressId = JsonUtil.getFieldValue(response, "addressId");
                String phone = JsonUtil.getFieldValue(response, "phone");
                String recipients = JsonUtil.getFieldValue(response, "recipients");
                String isDefault = JsonUtil.getFieldValue(response, "isDefault");
                edit_name.setText(recipients);
                edit_phone.setText(phone);
                edit_detailed_address.setText(addressDetail);
                text_address.setText(addressArea);
                  /* "isDefault": "是否默认 1-正常 2-默认",*/
                if (isDefault.equals("1")) {
                    cb_select.setChecked(false);
                    default_address.setTextColor(getResources().getColor(R.color.color_999999));
                } else if (isDefault.equals("2")) {
                    cb_select.setChecked(true);
                    default_address.setTextColor(getResources().getColor(R.color.color_333333));
                }

            } else {
                ToastUtil.showToast(errMsg);
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.preservation:
                /*保存*/

                goods_receipt_address = text_address.getText().toString();
                goods_receipt_name = edit_name.getText().toString();
                goods_receipt_phone = edit_phone.getText().toString();
                goods_receipt_address_d = edit_detailed_address.getText().toString();
                if (TextUtils.isEmpty(goods_receipt_name)) {
                    toast(R.string.text_edit_address);
                    return;
                } else if (TextUtils.isEmpty(goods_receipt_phone)) {
                    toast(R.string.toast_phone);
                    return;
                } else if (!StringUtil.isPhoneNumber(goods_receipt_phone)) {
                    toast(R.string.edit_need_phone_no);
                    return;
                } else if (goods_receipt_address.equals("省、市、区")) {
                    toast(R.string.text_choice_detailed_address);
                    return;
                } else if (TextUtils.isEmpty(goods_receipt_address_d)) {
                    toast(R.string.text_edit_detailed_address);
                    return;
                }


                String isDefault = cb_select.isChecked() + "";
                AddressBean addressBean = new AddressBean();
                addressBean.setToken(token);
                addressBean.setUserId(userId);
                addressBean.setRecipients(goods_receipt_name);
                addressBean.setPhone(goods_receipt_phone);
                addressBean.setAddressArea(goods_receipt_address);
                addressBean.setAddressDetail(goods_receipt_address_d);
                addressBean.setProvince(province);
                addressBean.setCity(city);
                addressBean.setCounty(county);
                if (isDefault.equals("true")) {
                    addressBean.setIsDefault("2");
                } else {
                    addressBean.setIsDefault("1");
                }

                if (isModify.equals("1")) {
                    /*修改*/
                    addressBean.setAddressId(addressId);
                    CommonInterface deliveryAddressInterface = new CommonInterface(DeliveryAddressActivity.this, new_httpListener);
                    deliveryAddressInterface.getInterface("16008", JSON.toJSONString(addressBean));

                } else {
                    /*新增*/
                    CommonInterface deliveryAddressInterface = new CommonInterface(DeliveryAddressActivity.this, new_httpListener);
                    deliveryAddressInterface.getInterface("16007", JSON.toJSONString(addressBean));
                }

                break;
            case R.id.address_selection:
                Intent intent = new Intent(DeliveryAddressActivity.this, ChoiceAreaActivity.class);
                startActivity(intent);

//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘  
//                popupWindow = new UtilPopupWindow();
//                //我再工具中没有写构造函数，这里调用默认的构造函数
//                WindowManager m = getWindowManager();
//                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//                final int windowHeight = d.getHeight();
//                //弹出框填充布局
//                LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_select_3, null);
//                RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_delivery_address, null);
//                popupWindow.setPopupWindow(DeliveryAddressActivity.this, windowHeight / 4, layout, layout2, Gravity.BOTTOM);
//                TextView btn_confirm = (TextView) layout.findViewById(R.id.btn_confirm);
//                TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
//                picker_province = (PickerView) layout.findViewById(R.id.picker_year);
//                picker_city = (PickerView) layout.findViewById(R.id.picker_month);
//                picker_diatrict = (PickerView) layout.findViewById(R.id.picker_day);
//                provinceList = new ArrayList<>();
//                cityList = new ArrayList<>();
//                diatrictList = new ArrayList<>();
//                settingProvince();
//                btn_cancel.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        popupWindow.dismiss();
//                    }
//                });
//                btn_confirm.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        // provinceName, cityName, diatrictName;
//                        text_address.setText(provinceName + cityName + diatrictName);
//                        popupWindow.dismiss();
//                    }
//                });

                break;
            default:
                break;
        }
    }

    //定义一个选中状态发生改变就会执行此类
    class CheckBoxListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == R.id.cb_select) {
                cb_select.setChecked(true);
            }
            if (isChecked) {
                //   toast("checked");
                cb_select.setChecked(true);
                default_address.setTextColor(getResources().getColor(R.color.color_333333));

            } else {
                //   toast("unchecked");
                cb_select.setChecked(false);
                default_address.setTextColor(getResources().getColor(R.color.color_999999));
            }
        }

    }

    HttpListener new_httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                DeliveryAddressActivity.this.finish();
                SharePreferencesHelper.getInstance(DeliveryAddressActivity.this).putString("isRefresh", "yes");
            } else {
                ToastUtil.showToast(errMsg);
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("失败");
        }
    };

    /**
     * 设置省份数据
     */
//    private void settingProvince() {
//        for (int i = 0; i < mProvinceDatas.length; i++) {
//            provinceList.add(mProvinceDatas[i]);
//        }
//        /**获取当前省份的名称*/
//        provinceName = provinceList.get(0);
//        picker_province.setData(provinceList);
//        picker_province.setSelected(0);
//        picker_province.setOnSelectListener(new PickerView.onSelectListener() {
//            @Override
//            public void onSelect(String text) {
//                provinceName = text;
//                cityList.clear();
//                diatrictList.clear();
//                settingCity(mCitisDatasMap, mDistrictDatasMap);
//            }
//        });
//        settingCity(mCitisDatasMap, mDistrictDatasMap);
//    }

    /*城市*/
//    private void settingCity(Map<String, String[]> mCitisDatasMap, final Map<String, String[]> mDistrictDatasMap) {
//
//
//        /**根据当前省份名称，更新市WheelView的信息*/
//        String[] cities = mCitisDatasMap.get(provinceName);
//        for (int i = 0; i < cities.length; i++) {
//            cityList.add(cities[i]);
//        }
//        /**获取当前城市*/
//        cityName = cityList.get(0);
//        picker_city.setData(cityList);
//        picker_city.setSelected(0);
//        picker_city.setOnSelectListener(new PickerView.onSelectListener() {
//
//            @Override
//            public void onSelect(String text) {
//                cityName = text;
//                diatrictList.clear();
//                settingDiatrict(mDistrictDatasMap);
//            }
//        });
//        settingDiatrict(mDistrictDatasMap);
//    }
//
//    private void settingDiatrict(Map<String, String[]> mDistrictDatasMap) {
//
//        /**根据当前城市名称，更新区WheelView的信息*/
//        String[] areas = mDistrictDatasMap.get(cityName);
//        for (int i = 0; i < areas.length; i++) {
//            diatrictList.add(areas[i]);
//        }
//        diatrictName = diatrictList.get(0);
//        picker_diatrict.setData(diatrictList);
//        picker_diatrict.setSelected(0);
//        picker_diatrict.setOnSelectListener(new PickerView.onSelectListener() {
//            @Override
//            public void onSelect(String text) {
//                diatrictName = text;
//            }
//        });
//    }


}
